package com.aptemo.webetek.server.handlers;

import javax.servlet.http.HttpServletRequest;

import com.aptemo.webetek.client.commands.Action;
import com.aptemo.webetek.client.exceptions.BackendException;
import com.aptemo.webetek.client.exceptions.WebetekLoginException;
import com.aptemo.webetek.server.CommonService;
import com.aptemo.webetek.server.datastore.DataStoreAPI;
import com.google.appengine.api.labs.taskqueue.Queue;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
import com.google.appengine.api.labs.taskqueue.TaskOptions;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.client.rpc.IsSerializable;

public abstract class ActionHandler<A extends Action<R>, R extends IsSerializable>
{

	protected UserService			userService			= UserServiceFactory.getUserService();

	protected DataStoreAPI			dataService;
	protected HttpServletRequest	rpcService;
	protected CommonService			utils				= new CommonService();

	protected static final long		TIME_FUSE_CONST		= 900000;								// 15
	protected static String			WEBETEK_ADMIN_EMAIL	= "webetek.online@gmail.com";

	protected ActionHandler(DataStoreAPI dataService)
	{
		this.dataService = dataService;
	}

	public abstract Class<? extends Action<?>> getActionType();

	public abstract R invoke(A action) throws BackendException, WebetekLoginException;

	protected void createEmailSenderTask(String from, String to, String cc, String subject, String content)
	{
		Queue queue = QueueFactory.getQueue("mail-queue");

		queue.add(TaskOptions.Builder.url("/workers/emailSender").param("from", from).param("to", to).param("cc", cc).param("subject", subject).param(
				"content", content));
	}

	protected String getServletUrl()
	{
		// TODO in case of unit test
		if (rpcService == null)
		{
			return "";
		}

		String scheme = rpcService.getScheme(); // http
		String serverName = rpcService.getServerName(); // hostname.com
		int serverPort = rpcService.getServerPort(); // 80
		String contextPath = rpcService.getContextPath(); // /mywebapp

		String url = scheme + "://" + serverName + ":" + serverPort + contextPath;
		return url;
	}

	public void setHttpServletRequest(HttpServletRequest service)
	{
		this.rpcService = service;
	}
}